package com.motu.vertx.module.utility.webhandler;

import com.motu.vertx.module.utility.base.ServerOpenBase;
import com.motu.vertx.module.utility.base.ServerOpenInterFace;
import com.motu.vertx.module.utility.commondata.ServeropenConfig;
import com.motu.vertx.module.utility.mysql.MysqlClient;
import com.motu.vertx.module.utility.mysql.MysqlTool;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import com.motu.vertx.module.utility.webtool.BaseWebHandler;
import com.motu.vertx.module.utility.webtool.SearchCondition;
import io.vertx.core.CompositeFuture;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.client.WebClient;
import io.vertx.sqlclient.Pool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

import static com.motu.vertx.module.utility.base.ServerOpenBase.serverOpenInterFace;

// 自动开服
public class ServeropenHandler extends BaseWebHandler{
	private static Logger logger = LoggerFactory.getLogger(ServeropenHandler.class);

	// 服务器开服设定的页面信息
	public static void openServerMainInfo(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		String sql1 = "select * from server_info order by server_id desc;";
		Future<JsonArray> fut1 = MysqlTool.queryJsonArrayFromDb(MysqlClient.getServerPool(), sql1, new JsonArray());// 读取服务器信息

		String sql2 = "select * from serveropen_order where opentime > ? order by opentime asc;";
		Future<JsonArray> fut2 = MysqlTool.queryJsonArrayFromDb(MysqlClient.getServerPool(), sql2, new JsonArray().add(TimeUtils.getCurTime()));// 读取预约开服信息

		String sql3 = "select * from serveropen_config order by id asc limit 1;";
		Future<JsonArray> fut3 = MysqlTool.queryJsonArrayFromDb(MysqlClient.getServerPool(), sql3, new JsonArray());// 读取预约开服信息

		CompositeFuture.all(fut1, fut2, fut3).onComplete(ar->{
			if (ar.succeeded()){
				JsonObject result = new JsonObject();
				result.put("server_list", fut1.result());// 服务器信息
				result.put("order_list", fut2.result());// 预约信息
				result.put("config_list", fut3.result());// 自动开服信息
				sendHttpResponse(routingContext.response(), result);
			} else{
				sendHttpResponseError(routingContext.response(), ar.cause().getMessage());
			}
		});
	}


	// 立即开1个新服 后台手动开服
	public static void openServerNow(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		int serverNum = 1;// 开服数量
		ServerOpenBase.serverOpenInterFace.doOpenServer(serverNum, ServerOpenBase.LOG_OPEN_TYPE_1, adminName);
		sendHttpResponse(routingContext.response(), new JsonObject());
	}

	// 开服日志查询
	public static void searchOpenServerLog(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		List<SearchCondition> scList = new ArrayList<SearchCondition>();
		if (json.containsKey("stime")) {
			json.put("stime", TimeUtils.getTimeStrIntValue(json.getString("stime")));
		}
		if (json.containsKey("etime")) {
			json.put("etime", TimeUtils.getTimeStrIntValue(json.getString("etime")));
		}
		scList.add(new SearchCondition("stime", ">=", new String[]{"addtime"}, null));
		scList.add(new SearchCondition("etime", "<=", new String[]{"addtime"}, null));
		searchFromTable(routingContext, MysqlClient.getServerPool(), json, "serveropen_log", scList);
	}

	// 添加一条预约开服信息
	public static void addServerOpenOrder(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		HttpServerResponse response = routingContext.response();
		String sql = "insert into serveropen_order (operator,servernum,opentime,addtime) values (?,?,?,?);";
		JsonArray params = new JsonArray();
		params.add(adminName);
		params.add(json.getInteger("servernum"));
		params.add(json.getInteger("opentime"));
		params.add(TimeUtils.getCurTime());
		MysqlTool.insertAndGetID(MysqlClient.getServerPool(), sql, params, handler->{
			if (handler.succeeded()){
				String content = "添加预约开服.开服时间:" + TimeUtils.getTimeFullStr(json.getInteger("opentime")) + " 开服数量:" + json.getInteger("servernum") + ".";// 日志内容
				ServerOpenBase.addLog(ServerOpenBase.LOG_OPEN_TYPE_2, content, adminName, new JsonArray());
				sendHttpResponse(response, new JsonObject());
			} else{
				sendHttpResponseError(response, handler.cause().getMessage());
			}
		});
	}

	// 获取一条预约开服信息
	public static void getoneServerOpenOrder(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		getFromTable(routingContext, MysqlClient.getServerPool(), "serveropen_order");
	}

	// 修改预约开服信息
	public static void updateServerOpenOrder(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		HttpServerResponse response = routingContext.response();
		String sql = "update serveropen_order set servernum=?,opentime=? where id=?;";
		JsonArray params = new JsonArray();
		params.add(json.getInteger("servernum"));
		params.add(json.getInteger("opentime"));
		params.add(json.getLong("id"));
		MysqlTool.updateToDb(MysqlClient.getServerPool(), sql, params, handler->{
			if (handler.succeeded()){
				String content = "修改预约开服.开服时间:" + TimeUtils.getTimeFullStr(json.getInteger("opentime")) + " 开服数量:" + json.getInteger("servernum") + ".";// 日志内容
				ServerOpenBase.addLog(ServerOpenBase.LOG_OPEN_TYPE_2, content, adminName, new JsonArray());
				sendHttpResponse(response, new JsonObject());
			} else{
				sendHttpResponseError(response, handler.cause().getMessage());
			}
		});
	}

	// 删除预约开服信息
	public static void delServerOpenOrder(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		HttpServerResponse response = routingContext.response();
		String sql = "delete from serveropen_order where id=?;";
		JsonArray params = new JsonArray();
		params.add(json.getLong("id"));
		MysqlTool.updateToDb(MysqlClient.getServerPool(), sql, params, handler->{
			if (handler.succeeded()){
				String content = "删除预约开服.开服时间:" + TimeUtils.getTimeFullStr(json.getInteger("opentime")) + " 开服数量:" + json.getInteger("servernum") + ".";// 日志内容
				ServerOpenBase.addLog(ServerOpenBase.LOG_OPEN_TYPE_2, content, adminName, new JsonArray());
				sendHttpResponse(response, new JsonObject());
			} else{
				sendHttpResponseError(response, handler.cause().getMessage());
			}
		});
	}

	// 获取一条自动开服的配置信息
	public static void getoneServerOpenConfig(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		HttpServerResponse response = routingContext.response();
		String sql3 = "select * from serveropen_config order by id asc limit 1;";
		MysqlTool.queryJsonArrayFromDb(MysqlClient.getServerPool(), sql3, new JsonArray(), handler->{
			if (handler.succeeded()) {
				sendHttpResponse(response, handler.result().getJsonObject(0));
			} else {
				sendHttpResponseError(response, handler.cause().getMessage());
			}
		});
	}

	// 修改自动开服的配置信息
	public static void updateServerOpenConfig(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		HttpServerResponse response = routingContext.response();
		JsonArray params = new JsonArray();
		String sql = "";
		if (json.getInteger("type") == 0) {// 条件开服
			sql = "update serveropen_config set is_close=?,type=?,server_num=?,check_type=?,param=?,param2=?,periodic_time=?,start_time=?,end_time=?,game_name=?,interval_day=?,next_time=?,week=? where id=?;";
			params.add(json.getInteger("is_close"));
			params.add(json.getInteger("type"));
			params.add(json.getInteger("server_num"));
			params.add(json.getInteger("check_type"));
			params.add(json.getInteger("param"));
			params.add(json.getInteger("param2"));
			params.add(json.getInteger("periodic_time"));
			params.add(json.getString("start_time"));
			params.add(json.getString("end_time"));
			params.add(json.getString("game_name"));
			params.add(json.getInteger("interval_day"));
			params.add(json.getLong("next_time"));
			params.add(json.getString("week"));
			params.add(json.getInteger("id"));
		} else {// 时间开服
			sql = "update serveropen_config set is_close=?,type=?,server_num=?,hour=?,game_name=?,interval_day=?,next_time=?,week=? where id=?;";
			params.add(json.getInteger("is_close"));
			params.add(json.getInteger("type"));
			params.add(json.getInteger("server_num"));
			params.add(json.getString("hour"));
			params.add(json.getString("game_name"));
			params.add(json.getInteger("interval_day"));
			params.add(json.getLong("next_time"));
			params.add(json.getString("week"));
			params.add(json.getInteger("id"));
		}
		MysqlTool.updateToDb(MysqlClient.getServerPool(), sql, params, handler->{
			if (handler.succeeded()){
				String content = "设定自动开服.";
				if (json.getInteger("type") == ServerOpenBase.AUTOOPEN_TYPE_0) {
					content += "开服方式:条件开服.条件参数:";
					if (json.getInteger("check_type") == ServerOpenBase.CHECK_TYPE_0) {
						content += "注册人数(设备排重)满" + json.getInteger("param") + "人.开服数量:" + json.getInteger("server_num");
					} else if (json.getInteger("check_type") == ServerOpenBase.CHECK_TYPE_1) {
						content += "角色等级达到" + json.getInteger("param2") + "级满" + json.getInteger("param") + "人.开服数量:" + json.getInteger("server_num");
					} else if (json.getInteger("check_type") == ServerOpenBase.CHECK_TYPE_2) {
						content += "付费用户人数(设备排重)满" + json.getInteger("param") + "人.开服数量:" + json.getInteger("server_num");
					}
				} else if (json.getInteger("type") == ServerOpenBase.AUTOOPEN_TYPE_1) {
					content += "开服方式:时间开服.每天的整点" + json.getString("hour") + ".开服数量:" + json.getInteger("server_num");
				}
				ServerOpenBase.addLog(ServerOpenBase.LOG_OPEN_TYPE_0, content, adminName, new JsonArray());
				sendHttpResponse(response, new JsonObject());
			} else{
				sendHttpResponseError(response, handler.cause().getMessage());
			}
		});
	}

	// 统计最新服务器的注册人数,后台手动开服，提升显示用
	public static void countLastServer(RoutingContext routingContext,JsonObject json,String adminName,WebClient client){
		int serverId = Future.await(ServerOpenBase.getLastServerId());
		int num = Future.await(ServerOpenBase.getUserNumByServerId(serverId));
		JsonObject result = new JsonObject();
		result.put("server_id", serverId);
		result.put("num", num);
		sendHttpResponse(routingContext.response(), result);
	}

	// 重载开服设定
	public static void reloadServerOpen(RoutingContext routingContext,JsonObject json,String adminName,WebClient client) {
		HttpServerResponse response = routingContext.response();
		ServerOpenBase.reload();
		ServerOpenBase.addLog(ServerOpenBase.LOG_OPEN_TYPE_0, "重载开服设定", adminName, new JsonArray());
		sendHttpResponse(response, new JsonObject());
	}
}
